import { environment } from '../../../environments/environment'

import { storeFreeze } from 'ngrx-store-freeze'

import { ActionReducer, ActionReducerMap, MetaReducer, createFeatureSelector, createSelector } from '@ngrx/store'

import * as fromUser from './user'
import * as fromChecklist from './checklist'
import * as fromRouter from '@ngrx/router-store'

export interface IState {
  user: fromUser.IState
  checklist: fromChecklist.IState,
  router: fromRouter.RouterReducerState
}

export const reducers: ActionReducerMap<IState> = {
  user: fromUser.reducer,
  checklist: fromChecklist.reducer,
  router: fromRouter.routerReducer
}

export function debug (reducer: ActionReducer<IState>): ActionReducer<IState> {
  return (state: IState, action: any): IState => {
    console.log('state', state)
    console.log('action', action)
    return reducer(state, action)
  }
}

export const metaReducers: Array<MetaReducer<IState>>
  = !environment.production
  ? [debug]
  : []

/**
 * user selectors
 */
const getUserState = createFeatureSelector<fromUser.IState>('user')
export const selectUserEntity = createSelector(getUserState, fromUser.selectEntity)
export const selectIsRegistered = createSelector(getUserState, fromUser.selectIsRegistered)
export const selectIsLogon = createSelector(getUserState, fromUser.selectIsLogon)
export const selectUserEntityId = createSelector(selectUserEntity, (u) => u.id)
/**
 * checklist selectors
 */
const getChecklistState = createFeatureSelector<fromChecklist.IState>('checklist')
export const selectChecklists = createSelector(getChecklistState, fromChecklist.selectChecklists)
export const selectTodayTasks = createSelector(getChecklistState, fromChecklist.selectTodayTasks)
export const selectTodayUnfinishedTasksCount = createSelector(
  selectTodayTasks,
  (u) => u.filter((v) => v.isDone === false).length)
export const selectTodoListId = createSelector(selectChecklists, (u) => u.find((v) => v.isStatic).id)
